import React from "react"
import { useReducer } from "react"

const initial = {
    n: 0,msg:"121"
}
/* 错误案例,需要对象的解构 */
const reducer = (state, action) => {
    console.log(state)
    if (action.type === 'add') {
        return { n: state.n + action.number }
        /*  return { n: state.n + action.number } */
    } else if (action.type = "multi") {
        return { n: state.n - action.number }
    } else {
        throw new Error("未知类型")
    }
}

const DemoUseReducer = () => {
    const [state, dispatch] = useReducer(reducer, initial)
    const add = () => {
        dispatch({ type: "add", number: 1 })
    }
    return (
        <>
            <div>{state.n}</div>
            <button onClick={add}>+1</button>
            <button onClick={() => dispatch({ type: "multi", number: 3 })}>-3</button>
        </>
    )
}

export default DemoUseReducer